from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .models import Interior,User,PaperName,Userdaan,Student,Personal
from django.urls import reverse
import sys
sys.path.append(r'..')
from paper.models import QuestionType,Subject
from openpyxl import load_workbook
import os



# Create your views here.





def enter(request):
    return render(request,'user/enter.html')


def register(request):
    return render(request,'user/register.html')

def pla(request):
    user = request.POST['user_name']
    pswd = request.POST['pswd']
    coding = request.POST['coding']
    try:
        bianma = Interior.objects.get(interior_cod = coding)
    except:
        return HttpResponse('未找到这个编码')
    else:
        try:
            u = User.objects.create(userid = user,pswd = pswd)
        except:
            return HttpResponse('账号已存在')
        bianma.delete()
    u.personal_set.create()
    return HttpResponse("""<a href = '/user/enter/'>注册成功，请返回登录吧</a>
                            
                            """)

def succeed(request):
    try:
        user = request.POST['userid']
        pswd = request.POST['pswd']
        a = User.objects.get(userid = str(user))
    except:
        return HttpResponse('账号不存在')
    else:
        if pswd == a.pswd:
            return HttpResponseRedirect(reverse('user:select', args=(user,)))
        else:
            return HttpResponse('密码不对')
    

def select(request,user_id):
    context = {'user_id':user_id}
    return render(request,'user/select.html',context)




def topic_subject(request,user_id):
    subjects = Subject.objects.all()
    context = {'subjects':subjects,'user_id':user_id}
    return render(request,'user/topic_subject.html',context)


def create(request,user_id,subject):
    subject = Subject.objects.get(subject_text = subject)
    question_type_set = subject.questiontype_set.all()
    question_list = []
    for i in question_type_set:
        question_list.append(len(i.question_set.all()))
    context = {'question_type_set':question_type_set,'question_list':question_list,'user_id':user_id,'subject':subject.subject_text}
    return render(request,'user/create.html',context)



'''
def topic_name(request,user_id):
    '''

def chuan(request):
    quh = dict(request.POST)
    return quh

def huodeti(request,user_id,subject):
    qu = chuan(request)
    userid = User.objects.get(userid = user_id)
    subject = Subject.objects.get(subject_text = subject)
    paper_name = qu['paper_name']
    bank = qu['xx']
    amount = qu['数量']
    score = qu['分数']
    try:
        userid.papername_set.get(paper_name_text = paper_name[0])
    except:
        paper = userid.papername_set.create(paper_name_text = paper_name[0],subject = subject)
        paper.userdaan_set.create(question_bank = bank,question_amount = amount,question_score = score)
        return HttpResponseRedirect(reverse('user:select',args = (user_id,)))
    else:
        return HttpResponse('已经有这个试卷名字了,请返回重新创建')
    





#录入学生信息
def student(request):
    return render(request,'user/student.html')


def shangzhuan(request):
    if request.method == "POST":    # 请求方法为POST时，进行处理  
        myFile =request.FILES.get("excel", None)    # 获取上传的文件，如果没有文件，则默认为None  
        if not myFile:  
            returnHttpResponse("没有文件上传!")  
        destination = open(os.path.join(r"media/",myFile.name),'wb+')    # 打开特定的文件进行二进制的写操作  
        for chunk in myFile.chunks():      # 分块写入文件  
            destination.write(chunk)  
        destination.close()  
        return HttpResponseRedirect(reverse('user:luru',args = (myFile.name,)))


#把学生的信息写入数据库
def luru(request,file_name):
    wb = load_workbook('media/{}'.format(file_name))
    sheet = wb['Sheet1']
    row = sheet.max_row
    student_id = []
    for i in range(2,row+1):
        q = Student.objects.create(student_name = sheet['A'+str(i)].value,
                               student_age = sheet['B'+str(i)].value,
                               student_sex = sheet['C'+str(i)].value,
                               student_id = sheet['D'+str(i)].value,
                               student_cell = sheet['E'+str(i)].value
                               )
        student_id.append(q.id)
    return HttpResponseRedirect(reverse('learnuser:create_user',args = (student_id,file_name,)))



#展示个人资料的页面
def personal(request,user_id):
    userid = User.objects.get(userid = user_id)
    user_obj = userid.personal_set.all()[0]
    user_name = user_obj.screen_name
    user_conding = user_obj.paper_coding
    user_hua = user_obj.stimulate
    personal_id = user_obj.id
    context = {'user_id':user_id,'user_name':user_name,'personal_id':personal_id,'user_conding':user_conding,'user_hua':user_hua}
    #return HttpResponse(personal_id)
    return render(request,'user/personal.html',context)




#修改个人资料
def xiugai(request,user_id,personal_id):
    userid = User.objects.get(userid = user_id)
    info = request.POST
    user_name = info['user_name']
    user_hua = info['user_hua']
    user_conding = info['user_conding']
    user_obj = Personal.objects.get(pk = personal_id)
    user_obj.screen_name = user_name
    user_obj.paper_coding = user_conding
    user_obj.stimulate = user_hua
    user_obj.save()
    userid.encoding_text = user_conding
    userid.save()
    return HttpResponseRedirect(reverse('user:personal',args = (user_id,)))




































    
